﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using System.Runtime.Serialization;
using first_learn.GeocodeService;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using first_learn.GeocodeService;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using first_learn;
using Microsoft.Phone.Shell;
using System.Text;


namespace PhoneApp3
{
    public partial class MainPage : PhoneApplicationPage
    {
        GeoCoordinateWatcher watcher;
        string accuracyText = "";
        string This_address = "";
        double latitude = 0;
        double longitude = 0;
        Socket mySocket = null;
        string add = "sslab14.cs.purdue.edu";
        int port = 2345;
        ManualResetEvent MyEvent = null;
        //TcpClient myClient;
        static ManualResetEvent clientDone = new ManualResetEvent(false);

        // Constructor
        public MainPage()
        {
            StartLocationService(GeoPositionAccuracy.Default);
            InitializeComponent();
            UpdateImage();
            //PageTitle.Text = "West Lafayette";

            ApplicationBar = new ApplicationBar();//声明一个ApplicationBar 
            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;//设置应用程序栏可见
            ApplicationBar.IsMenuEnabled = true;//设置菜单项可用

            ApplicationBarIconButton button1 = new ApplicationBarIconButton(new Uri("/Icons/dark/appbar.feature.camera.rest.png", UriKind.Relative));//声明一个Button,并设置其图标路劲。
            button1.Text = "To Share";//图标显示的名称为Video
            button1.Click += new EventHandler(Share);//注册Click事件

            ApplicationBarIconButton button2 = new ApplicationBarIconButton(new Uri("/Icons/dark/appbar.feature.search.rest.png", UriKind.Relative));
            button2.Text = "Change City";
            button2.Click += new EventHandler(Change);

            ApplicationBarIconButton button3 = new ApplicationBarIconButton(new Uri("/Icons/dark/appbar.refresh.rest.png", UriKind.Relative));
            button3.Text = "Update";
            button3.Click += new EventHandler(Update);

            ApplicationBar.Buttons.Add(button1);//将Button添加到应用程序栏中，这样便可以使用该Button了。
            ApplicationBar.Buttons.Add(button2);
            ApplicationBar.Buttons.Add(button3);

            ApplicationBarMenuItem menuItem1 = new ApplicationBarMenuItem("About");//声明一个MenuItem项，并设置显示文字为电子书
            ApplicationBarMenuItem menuItem2 = new ApplicationBarMenuItem("Rate");
            ApplicationBarMenuItem menuItem3 = new ApplicationBarMenuItem("Exit");

            menuItem1.Click += new EventHandler(menuItem1_Click);//注册MenuItem项的Click事件
            menuItem2.Click += new EventHandler(menuItem2_Click);
            menuItem3.Click += new EventHandler(menuItem3_Click);


            ApplicationBar.MenuItems.Add(menuItem1);//将MenuItem添加到菜单栏中，这样便可以使用该MenuItem了。
            ApplicationBar.MenuItems.Add(menuItem2);
            ApplicationBar.MenuItems.Add(menuItem3);

        }

        public void UpdateImage()
        {
            //image
            image1.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(new Uri("http://sslab13.cs.purdue.edu:2345/1"));
            image2.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(new Uri("http://sslab13.cs.purdue.edu:2345/2"));
            image3.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(new Uri("http://sslab13.cs.purdue.edu:2345/3"));
            image4.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(new Uri("http://sslab13.cs.purdue.edu:2345/4"));
            image5.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(new Uri("http://sslab13.cs.purdue.edu:2345/5"));
            image6.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(new Uri("http://sslab13.cs.purdue.edu:2345/6"));
            image7.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(new Uri("http://sslab13.cs.purdue.edu:2345/7"));
            image8.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(new Uri("http://sslab13.cs.purdue.edu:2345/8"));

        }

        public static Guid GetId()
        {
            Guid applicationId = Guid.Empty;

            var productId = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("ProductID");

            if (productId != null && !string.IsNullOrEmpty(productId.Value))
                Guid.TryParse(productId.Value, out applicationId);

            return applicationId;
        }


        #region Application logic


        /// <summary>
        /// Helper method to start up the location data acquisition
        /// </summary>
        /// <param name="accuracy">The accuracy level </param>
        private void StartLocationService(GeoPositionAccuracy accuracy)
        {
            // Reinitialize the GeoCoordinateWatcher
            watcher = new GeoCoordinateWatcher(accuracy);
            watcher.MovementThreshold = 20;

            // Add event handlers for StatusChanged and PositionChanged events
            watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
            watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);

            // Start data acquisition
            watcher.Start();
        }

        /// <summary>
        /// Handler for the StatusChanged event. This invokes MyStatusChanged on the UI thread and
        /// passes the GeoPositionStatusChangedEventArgs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyStatusChanged(e));
        }
        /// <summary>
        /// Custom method called from the StatusChanged event handler
        /// </summary>
        /// <param name="e"></param>
        void MyStatusChanged(GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    // The location service is disabled or unsupported.
                    // Alert the user
                    //StatusTextBlock.Text = "location is unsupported on this device";
                    break;
                case GeoPositionStatus.Initializing:
                    // The location service is initializing.
                    // Disable the Start Location button
                    //StatusTextBlock.Text = "initializing location service," + accuracyText;
                    break;
                case GeoPositionStatus.NoData:
                    // The location service is working, but it cannot get location data
                    // Alert the user and enable the Stop Location button
                    //StatusTextBlock.Text = "data unavailable," + accuracyText;
                    break;
                case GeoPositionStatus.Ready:
                    // The location service is working and is receiving location data
                    // Show the current position and enable the Stop Location button
                    //StatusTextBlock.Text = "receiving data, " + accuracyText;
                    break;

            }
        }

        /// <summary>
        /// Handler for the PositionChanged event. This invokes MyStatusChanged on the UI thread and
        /// passes the GeoPositionStatusChangedEventArgs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyPositionChanged(e));
        }

        /// <summary>
        /// Custom method called from the PositionChanged event handler
        /// </summary>
        /// <param name="e"></param>
        void MyPositionChanged(GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            // Update the TextBlocks to show the current location
            //textBox1.Text = e.Position.Location.Latitude.ToString("0.000");
            //textBox2.Text = e.Position.Location.Longitude.ToString("0.000");
            latitude = e.Position.Location.Latitude;
            longitude = e.Position.Location.Longitude;
            GeocodeServiceClient client = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");

            client.ReverseGeocodeCompleted += new EventHandler<ReverseGeocodeCompletedEventArgs>(OnReverseGeocodeCompleted);

            ReverseGeocodeRequest request = new ReverseGeocodeRequest();
            request.Credentials = new first_learn.GeocodeService.Credentials();
            request.Credentials.ApplicationId = "AjjGZGtCVs7lEuRn860kGigumg5hhJ8LqKXOIxpk1zwuxxQUgcrFDRWmrYfYCtFg";
            Location loc = new Location();
            loc.Latitude = e.Position.Location.Latitude;
            loc.Longitude = e.Position.Location.Longitude;
            request.Location = loc;
            client.ReverseGeocodeAsync(request);
        }

        private void OnReverseGeocodeCompleted(object sender, ReverseGeocodeCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Results.Count >= 0)
                {
                    GeocodeResponse response = e.Result;

                    //textBox3.Text = response.Results[0].DisplayName;
                    This_address = response.Results[0].DisplayName;
                    string[] country = This_address.Split(',');
                    string[] state = country[2].Split(' ');
                    PageTitle.Text = country[1]+", "+state[1];
                    //System.Collections.ObjectModel.ObservableCollection<GeocodeResult> list = response.Results;
                    //string allName = "";
                    //foreach (GeocodeResult i in list)
                    //{
                    //    allName += i.DisplayName + "  ";
                    //}
                    //textBox3.Text = allName;
                }
                else
                    MessageBox.Show("Sorry, cannot find location!");
            }
        }

        #endregion

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            string msg = This_address;
            first_learn.ServiceReference1.Service1Client myClient = new first_learn.ServiceReference1.Service1Client();
            myClient.GetDataCompleted += new EventHandler<first_learn.ServiceReference1.GetDataCompletedEventArgs>(myClient_GetDataCompleted);
            myClient.GetDataAsync((int)latitude);
        }

        void myClient_GetDataCompleted(object sender, first_learn.ServiceReference1.GetDataCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
        }



        void Share(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPageFive.xaml", UriKind.Relative));
        }

        void Change(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPageThree.xaml", UriKind.Relative));

        }

        void Update(object sender, EventArgs e)
        {
            UpdateImage();
        }

        private void menuItem1_Click(object sender, System.EventArgs e)
        {
            // About 
            MessageBox.Show("About this app.");
        }

        private void menuItem2_Click(object sender, System.EventArgs e)
        {
            // Rate 
            MessageBox.Show("Rate this app!");
        }


        private void menuItem3_Click(object sender, System.EventArgs e)
        {
            // exit 
            throw new Exception("exit");
        }


    }
}